package com.bluesky.jwf.component.captcha;

import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.javawebbrowser.domain.html.tags.form.input.Text;
import com.bluesky.jwf.ComponentFactory;
import com.bluesky.jwf.component.Button;
import com.bluesky.jwf.component.Component;
import com.bluesky.jwf.component.event.AbstractEventHandler;

/**
 * it contains a image (url), optional a audio url, a text label, a text input
 * field and a change button.
 * 
 * @author jack
 * 
 */
public class Captcha extends Component {

	private Component questionContainer;
	private Tag changeTag;
	private Text answerTag;

	private Button changeButton;

	private String randomString;

	private CaptchaServiceProvider serviceProvider;

	public Captcha() {

	}

	@Override
	public void init(String html) {

		super.init(html);

		questionContainer = new Component();
		loadByJwfClass("questionContainer").replace(questionContainer);

		changeTag = loadByJwfClass("change");
		answerTag = (Text) loadByJwfClass("answer");

		changeButton = (Button) ComponentFactory.getInstance().createComponent(
				Button.class.getSimpleName());
		changeButton.setText("change");
		changeTag.replace(changeButton);
		changeButton.setClickHandler(new AbstractEventHandler() {

			@Override
			public void handle(Component target, Object parameter) {
				createNewCaptcha();
			}
		});

	}

	public CaptchaServiceProvider getServiceProvider() {
		return serviceProvider;
	}

	public void setServiceProvider(CaptchaServiceProvider serviceProvider) {
		this.serviceProvider = serviceProvider;

		createNewCaptcha();
	}

	public void setQuestion(String question) {
		questionContainer.setBodyAndParse(question);
	}

	@Override
	public void setId(String id) {
		super.setId(id);
		answerTag.setName(getId() + "_text");

	}

	/**
	 * the service instance will not be hold due to serialization reason
	 * 
	 * @param service
	 */
	public void createNewCaptcha() {
		CaptchaService service = serviceProvider.getService();
		randomString = service.generateRandomString();
		setQuestion(service.getQuestion(randomString));

	}

	public boolean isHuman() {
		CaptchaService service = serviceProvider.getService();
		return service.check(answerTag.getValue(), randomString);
	}

	@Override
	public void setPostBackData(String name, String value) {
		super.setPostBackData(name, value);

		if (name.equals("text"))
			answerTag.setValue(value);
	}

	public void setRandomString(String randomString) {
		this.randomString = randomString;
	}

	public String getAnswer() {

		return answerTag.getValue();
	}

	public void setAnswer(String answer) {
		answerTag.setValue(answer);
	}

}
